using Consul;

namespace WebApp8.Services
{
    public static class ConsulRegistration
    {
        public static IServiceCollection AddConsulConfig(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddSingleton<IConsulClient>(sp =>
            {
                var consulConfig = configuration.GetSection("Consul");
                var consulAddress = consulConfig["Address"] ?? "http://localhost:8500";
                Console.WriteLine($"Configuring Consul client with address: {consulAddress}");
                return new ConsulClient(cfg =>
                {
                    cfg.Address = new Uri(consulAddress);
                });
            });

            return services;
        }

        public static IApplicationBuilder UseConsul(this IApplicationBuilder app, IConfiguration configuration)
        {
            var consulClient = app.ApplicationServices.GetRequiredService<IConsulClient>();
            var lifetime = app.ApplicationServices.GetRequiredService<IHostApplicationLifetime>();
            var consulConfig = configuration.GetSection("Consul");

            var serviceId = $"{consulConfig["ServiceName"]}-{consulConfig["ServiceId"] ?? Guid.NewGuid().ToString()}";
            var serviceName = consulConfig["ServiceName"] ?? "WebApp8";
            var serviceAddress = consulConfig["ServiceAddress"] ?? "localhost";
            var servicePort = int.Parse(consulConfig["ServicePort"] ?? "5000");

            Console.WriteLine($"Registering service to Consul - ID: {serviceId}, Name: {serviceName}, Address: {serviceAddress}, Port: {servicePort}");

            var registration = new AgentServiceRegistration()
            {
                ID = serviceId,
                Name = serviceName,
                Address = serviceAddress,
                Port = servicePort,
                Tags = new[] { "WebAPI", "ASP.NET Core" },
                Check = new AgentServiceCheck()
                {
                    HTTP = $"http://{serviceAddress}:{servicePort}/health",
                    Timeout = TimeSpan.FromSeconds(3),
                    Interval = TimeSpan.FromSeconds(10)
                }
            };

            // 服务注册
            try
            {
                consulClient.Agent.ServiceRegister(registration).Wait();
                Console.WriteLine("Successfully registered service to Consul");

                // 验证服务注册
                var services = consulClient.Agent.Services().Result;
                if (services.Response.ContainsKey(serviceId))
                {
                    Console.WriteLine("Service registration verified");
                }
                else
                {
                    Console.WriteLine("Warning: Service registration could not be verified");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error registering service to Consul: {ex.Message}");
                throw;
            }

            // 应用程序终止时，取消服务注册
            lifetime.ApplicationStopping.Register(() =>
            {
                try
                {
                    Console.WriteLine($"Deregistering service {serviceId} from Consul");
                    consulClient.Agent.ServiceDeregister(registration.ID).Wait();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error deregistering service from Consul: {ex.Message}");
                }
            });

            return app;
        }
    }
} 